//
//  GoodsManagementController.m
//  tuanGG
//
//  Created by 微他 on 15/9/21.
//  Copyright (c) 2015年 weita. All rights reserved.
//

#import "GoodsManagementController.h"
#import "Header.h"
#import "GoodsManagementViewCell.h"
#import "AddGoodsController.h"
#import "LoginViewController.h"
//#import "NSData+WJCategory.h"
@interface GoodsManagementController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>;
@property (strong, nonatomic)UITableView            *tableView;
@property (assign, nonatomic)NSInteger              index;
@property (strong, nonatomic)UIView                 *line;
@property (strong, nonatomic)UISegmentedControl     *segControl;
@property (strong, nonatomic)NSArray                *array;
@property (strong, nonatomic)NSMutableArray         *alreadySource;
@property (strong, nonatomic)NSMutableArray         *notSource;
@property (strong, nonatomic)NSDictionary           *dictionary;
@property (strong, nonatomic)NSString               *urlString;
@property (strong, nonatomic)NSDictionary           *goodsDictionary;
@property (assign, nonatomic)NSInteger               mode;
@end

@implementation GoodsManagementController
- (void)button {
    if (_buttonBlock) {
        _buttonBlock();
    }
}
- (void)viewWillAppear:(BOOL)animated{
    _index = 0;
    _mode = 0;
    [_tableView headerBeginRefreshing];
    _alreadySource = [NSMutableArray array];
    _notSource= [NSMutableArray array];
    [self tabBarShow];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavView];
    [self addnavigationTitle:@"商品管理" navColor:@"4fd2be"];
    self.view.backgroundColor = [UIColor colorWithHexString:@"f0efed"];
    [self initTitle];

    
}
- (void) initlizeDataSource {
    _goodsDictionary = [NSDictionary dictionary];
}
- (void)initNavView {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"添加"] style:UIBarButtonItemStylePlain target:self action:@selector(addButton)];
}
- (void)initTitle {
    _array = @[@"已上架",@"未上架"];
    _segControl = [[UISegmentedControl alloc]initWithItems:_array];
    _segControl.frame = CGRectMake(0, 0, ScreenWidth, 46);
    _segControl.selectedSegmentIndex = 0;
    _segControl.tintColor = [UIColor clearColor];
    _segControl.backgroundColor = [UIColor whiteColor];
    //选中状态
    NSDictionary *selectedTextttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"969696"]};
    [_segControl setTitleTextAttributes:selectedTextttributes forState:UIControlStateSelected];
    NSDictionary *unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],
                                               NSForegroundColorAttributeName: [UIColor colorWithHexString:@"969696"]};
    [_segControl setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    [self.view addSubview:_segControl];
    [_segControl addTarget:self action:@selector(shelvesButton:) forControlEvents:UIControlEventValueChanged];
    _segControl.tag = 1;
    _line = [[UIView alloc]initWithFrame:CGRectMake(0, 45, ScreenWidth/2, 2)];
    _line.backgroundColor = [UIColor colorWithHexString:@"4fd2be"];
    [_segControl addSubview:_line];
    
    UIView *lines = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, _segControl.frame.size.height-10)];
    lines.backgroundColor = [UIColor blackColor];
    lines.alpha = 0.1;
    lines.center = CGPointMake(ScreenWidth/2, _segControl.frame.size.height/2);
    [_segControl addSubview:lines];

    [self addtableView];
}

- (void)addtableView {
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 46, ScreenWidth, ScreenHeight-160) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[GoodsManagementViewCell class] forCellReuseIdentifier:@"CELL"];
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing:)];
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing:)];
    [self.view addSubview:_tableView];
    
}
#pragma mark - 事件实现
- (void)shelvesButton:(UISegmentedControl *)sender {
    if (sender.tag == 1) {
        if (sender.selectedSegmentIndex == 0) {
            NSLog(@"已上架");

            [_tableView reloadData];
            [self alreadyshelves];
            _index = 0;
        }else if (sender.selectedSegmentIndex == 1 ){
            NSLog(@"未上架");
            [_tableView reloadData];
            [self noShelves];
            _index = 1;
        }
    }
}
- (void)addButton {
        NSLog(@"进行添加");
        AddGoodsController *addGoodsVC = [[AddGoodsController alloc]init];
        [self.navigationController pushViewController:addGoodsVC animated:YES];
}
- (void)footerRereshing:(NSInteger)sender {
    [self networking];
}
- (void)headerRereshing:(NSInteger)sender {
    _urlString = goodsList_url;
    if (_segControl.selectedSegmentIndex == 0) {
        _dictionary = @{@"type":@"1"};
    }else{
        _dictionary = @{@"type":@"0"};
    }
    [self networking];
}
- (void)GoodsButton:(UIButton *)sender {
    NSLog(@"%d",sender.tag);
     if(sender.tag < 100){
        _mode = YES;
        _goodsDictionary = @{@"ispublish":@"0",@"facevalue":_alreadySource[sender.tag][@"facevalue"],@"editdateline":_alreadySource[sender.tag][@"editdateline"]};
        [self Goodsrequest];
        NSLog(@"下架");
    }else if (sender.tag >= 100){
        if (_alreadySource.count < 3) {
            _mode = YES;
            NSLog(@"%d",sender.tag);
            _goodsDictionary = @{@"ispublish":@"1",@"facevalue":_notSource[sender.tag-100][@"facevalue"],@"editdateline":_notSource[sender.tag-100][@"editdateline"]};
            [self Goodsrequest];
        }else {
            [Common addAlert:@"上架商品上限为3个"];
        }

        NSLog(@"上架");
    }
}
#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsManagementViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath ];
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 46, ScreenWidth, ScreenHeight)];
        imageView.backgroundColor = [UIColor blueColor];
//        [_tableView addSubview:imageView];
        NSLog(@"%d",_segControl.selectedSegmentIndex);
        if (_segControl.selectedSegmentIndex == 0) {

            cell.nameIamge.image = [UIImage imageNamed:[NSString stringWithFormat:@"%zi元代金劵",[_alreadySource[indexPath.section][@"facevalue"]integerValue]]];
            cell.nameLabel.text = [NSString stringWithFormat:@"%@元代金劵",_alreadySource[indexPath.section][@"facevalue"]];
            cell.dateLabel.text = [NSString stringWithFormat:@"%@ 到期",[NSDate dateInitTwo:[_alreadySource[indexPath.section][@"datelimite"]integerValue]]];
            cell.priceLabel.text = [NSString stringWithFormat:@"%@元",_alreadySource[indexPath.section][@"price"]];
            
        }else if(_segControl.selectedSegmentIndex == 1){
            if (_notSource.count != 0) {
                cell.nameIamge.image = [UIImage imageNamed:[NSString stringWithFormat:@"%zi元代金劵",[_notSource[indexPath.section][@"facevalue"]integerValue]]];
                cell.nameLabel.text = [NSString stringWithFormat:@"%@元代金劵",_notSource[indexPath.section][@"facevalue"]];
                cell.dateLabel.text = [NSString stringWithFormat:@"%@ 到期",[NSDate dateInitTwo:[_notSource[indexPath.section][@"datelimite"]integerValue]]];
                cell.priceLabel.text = [NSString stringWithFormat:@"%@元",_notSource[indexPath.section][@"price"]];
            }
            
        }


        
        [cell.shelvesButton addTarget:self action:@selector(GoodsButton:) forControlEvents:UIControlEventTouchUpInside];
        if (_index == 1) {
            [cell.shelvesButton setTitle:@"上架" forState:UIControlStateNormal];
            cell.shelvesButton.tag = indexPath.section+100;
        }if (_index == 0) {
            [cell.shelvesButton setTitle:@"下架" forState:UIControlStateNormal];
            cell.shelvesButton.tag = indexPath.section;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.jon =^(){
        AddGoodsController *addGoodsVC = [[AddGoodsController alloc]init];
        addGoodsVC.dictionary = [NSDictionary dictionary];
        [self.navigationController pushViewController:addGoodsVC animated:YES];
        if (_segControl.selectedSegmentIndex == 0) {
            addGoodsVC.dictionary = [_alreadySource[indexPath.section]mutableCopy];
        }else{
            addGoodsVC.dictionary = [_notSource[indexPath.section]mutableCopy];
        }
        };
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_segControl.selectedSegmentIndex == 0) {
        return _alreadySource.count;
    }else{
        return _notSource.count;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}
- (void)alreadyshelves
{
    //已经上架
    [UIView animateWithDuration:0.1 animations:^{
        _line.frame = CGRectMake(0, 45, ScreenWidth / 2, 2);
    }];
    [_tableView headerBeginRefreshing];
}

- (void)noShelves
{
    //未上架
    [UIView animateWithDuration:0.1 animations:^{
        _line.frame = CGRectMake(ScreenWidth / 2, 45, ScreenWidth / 2, 2);
    }];
    [_tableView headerBeginRefreshing];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        NSLog(@"退出");
        LoginViewController *login = [[LoginViewController alloc]init];
        [self.navigationController pushViewController:login animated:YES];
    }
}

#pragma mark - 网络请求
- (void)networking {
    [GLAFRequest startRequest:goodsList_url paramsDic:_dictionary defaultdialog:NO ispost:NO handleSuccess:^(id sta, NSDictionary *paramsDic) {
        NSLog(@"%@",sta);
        NSLog(@"商品列表：%d",[sta[@"productlist"]count]);


        if ([sta[@"code"]integerValue] == 1 && [sta[@"productlist"]count] != 0 && [_dictionary[@"type"]integerValue] == 0) {
            _notSource = [NSMutableArray array];
            _notSource = [sta[@"productlist"]mutableCopy];

        }else if([sta[@"code"]integerValue] == 1 && [sta[@"productlist"]count] != 0 && [_dictionary[@"type"]integerValue] == 1){
            _alreadySource = [NSMutableArray array];
            _alreadySource= [sta[@"productlist"]mutableCopy];
        }else {

        }

        [_tableView reloadData];

    } doFinally:^(NSDictionary *paramsDic) {

        [_tableView headerEndRefreshing];
        [_tableView footerEndRefreshing];
    }];
}
- (void)Goodsrequest {
    [GLAFRequest startRequest:goodisputway_url paramsDic:_goodsDictionary defaultdialog:YES ispost:YES handleSuccess:^(id sta, NSDictionary *paramsDic) {
        NSLog(@"%@",sta);
        if ([sta[@"code"]integerValue] == 1) {
            if (_index == 1) {
                [Common addAlert:@"上架成功"];
            }else{
                [Common addAlert:@"下架成功"];
            }
            [self headerRereshing:_index];

            [_tableView reloadData];
        }
    } doFinally:^(NSDictionary *paramsDic) {

    }];
}
- (void)dealloc {
    [_tableView removeFromSuperview];
    [_tableView removeFooter];
    [_tableView removeHeader];
}
@end
